package com.geeklan.smart.ui.main.frament;

import android.graphics.Color;
import android.graphics.drawable.ColorDrawable;
import android.os.Handler;
import android.os.Message;
import android.text.TextUtils;
import android.view.SurfaceView;
import android.view.View;
import android.view.ViewGroup;
import android.widget.FrameLayout;
import android.widget.Toast;

import androidx.annotation.NonNull;
import androidx.appcompat.content.res.AppCompatResources;
import androidx.constraintlayout.widget.ConstraintLayout;
import androidx.core.app.ActivityCompat;
import androidx.lifecycle.ViewModelProvider;
import androidx.recyclerview.widget.LinearLayoutManager;

import com.geeklan.base.base.BaseFragment;
import com.geeklan.base.utils.MLog;
import com.geeklan.smart.MLMApplication;
import com.geeklan.smart.R;
import com.geeklan.smart.data.model.Device;
import com.geeklan.smart.data.remote.rtc.RtcEngineManager;
import com.geeklan.smart.data.repository.device.DeviceRepository;
import com.geeklan.smart.data.repository.msg.CommonRepository;
import com.geeklan.smart.databinding.FragmentHomeBinding;
import com.geeklan.smart.databinding.HomeDeviceItemBinding;
import com.geeklan.smart.event.LoginOut;
import com.geeklan.smart.permission.PermissionManager;
import com.geeklan.smart.ui.device.DeviceInfoActivity;
import com.geeklan.smart.ui.device.VideoCallActivity;
import com.geeklan.smart.ui.message.MessageListActivity;
import com.geeklan.smart.ui.network.DeviceNetworkOneActivity;
import com.geeklan.smart.ui.viewmodel.common.CommonViewModel;
import com.geeklan.smart.ui.viewmodel.common.CommonViewModelFactory;
import com.geeklan.smart.ui.viewmodel.device.DeviceViewModel;
import com.geeklan.smart.ui.viewmodel.device.DeviceViewModelFactory;
import com.geeklan.smart.utils.GlideUtils;
import com.geeklan.smart.utils.SharedPreferencesUtil;
import com.geeklan.smart.widget.RoundedImageView;

import org.greenrobot.eventbus.Subscribe;
import org.greenrobot.eventbus.ThreadMode;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;


public class HomeFragment extends BaseFragment<FragmentHomeBinding> {
    private DeviceViewModel deviceViewModel;
    private CommonViewModel mViewModel;
    private List<Device> deviceList = new ArrayList<>();
    private Map<String,HomeDeviceItemBinding> homeDeviceItemBindingMap = new HashMap<>();
    private RtcEngineManager rtcEngineManager;
    private RtcEngineManager rtcEngineManager1;
    private String token;
    private String token1;
    private String deviceId;

    private int userId;


    @Override
    public boolean isRegisterEvent() {
        return true;
    }

    @Override
    protected FragmentHomeBinding initBinding() {
        return FragmentHomeBinding.inflate(getLayoutInflater());
    }

    @Override
    protected void initData() {
        userId = SharedPreferencesUtil.getInt("userId", 0);
        deviceViewModel = new ViewModelProvider(this, new DeviceViewModelFactory(new DeviceRepository())).get(DeviceViewModel.class);

        deviceViewModel.getDeviceListLiveData().observe(this, response -> {
            dismiss();
            deviceList.clear();
            deviceList.addAll(response.getData());
            homeDeviceItemBindingMap.clear();
            mBinding.rvDeviceList.removeAllViews();


            mBinding.swipeRefreshLayout.finishRefresh();

            if (deviceList.isEmpty()) {
                mBinding.llNotData.setVisibility(View.VISIBLE);
                mBinding.rvDeviceList.setVisibility(View.GONE);
            } else {
                mBinding.llNotData.setVisibility(View.GONE);
                mBinding.rvDeviceList.setVisibility(View.VISIBLE);

                String[] deviceIds = new String[deviceList.size()];
                for (int i = 0; i < deviceList.size(); i++) {
                    deviceIds[i] = deviceList.get(i).getDeviceId();

                    HomeDeviceItemBinding hBinding = HomeDeviceItemBinding.inflate(getLayoutInflater());
                    initDeviceItemUI(deviceList.get(i),hBinding);
                    homeDeviceItemBindingMap.put(deviceList.get(i).getDeviceId(),hBinding);
                    mBinding.rvDeviceList.addView(hBinding.getRoot());
                }
                MLMApplication.getUmeng().addTags(deviceIds);
            }
        });

        deviceViewModel.getErrorLiveData().observe(this, s -> {
            dismiss();
            Toast.makeText(mContext, s, Toast.LENGTH_SHORT).show();
            mBinding.swipeRefreshLayout.finishRefresh();
        });

        mViewModel = new ViewModelProvider(this, new CommonViewModelFactory(new CommonRepository())).get(CommonViewModel.class);

        mViewModel.getBannerListLiveData().observe(this, response -> {
            if (response != null && !response.getList().isEmpty()) {
                mBinding.banner.setBannerData(response.getList());
            }
        });
        mViewModel.getAppBanner();

        if (PermissionManager.checkPermissions(getActivity())) {
            deviceAccessTokenLiveData();
        } else {
            ActivityCompat.requestPermissions(getActivity(), PermissionManager.getRequiredPermissions(), PERMISSION_REQ_ID);
        }

        mViewModel = new ViewModelProvider(this, new CommonViewModelFactory(new CommonRepository())).get(CommonViewModel.class);

        mViewModel.getMsgListLiveData().observe(this, response -> {
            if (response.getData() != null && !response.getData().isEmpty()) {
                mBinding.redView.setVisibility(View.VISIBLE);
            } else {
                mBinding.redView.setVisibility(View.GONE);
            }
        });
    }

    private void deviceAccessTokenLiveData() {
        deviceViewModel.getDeviceLiveData().observe(this, apiResponse -> {
            dismiss();
            token = apiResponse.getData().getToken();
            initRtc(0);
        });

        deviceViewModel.getDeviceLiveData1().observe(this, apiResponse -> {
            dismiss();
            token1 = apiResponse.getData().getToken();
            initRtc(1);
        });
    }
    
    private void initDeviceItemUI(Device device, HomeDeviceItemBinding hBinding){
        String deviceId = device.getDeviceId();
        String deviceId_4;
        try {
            deviceId_4 = deviceId.substring(deviceId.length() - 4);
        } catch (Exception e) {
            deviceId_4 = "";
        }
        hBinding.tvPetName.setText(device.getDeviceName() + "(" + deviceId_4 + ")");

//        hBinding.ivPhoto.setVisibility(View.VISIBLE);
//        hBinding.llLookTa.setVisibility(View.VISIBLE);
//        hBinding.remoteVideoViewContainer.setVisibility(View.INVISIBLE);
//        hBinding.ivCloseVideo.setVisibility(View.INVISIBLE);
//        hBinding.ivVideoFullScreen.setVisibility(View.INVISIBLE);

        hBinding.tvAuto.setText(device.getAutoFeedState() == 0 ? mContext.getString(R.string.not_open) : mContext.getString(R.string.open));
        hBinding.tvSolidFoodState.setText(device.getSolidFoodState() == 1 ? mContext.getString(R.string.sufficient) : mContext.getString(R.string.impatient));
        hBinding.tvCatStripsState.setText(device.getCatStripsState() == 1 ? mContext.getString(R.string.sufficient) : mContext.getString(R.string.impatient));
        if (device.getSolidFoodState() != 1) {
            hBinding.tvSolidFoodState.setCompoundDrawablesWithIntrinsicBounds(0, 0, R.drawable.ic_home_device_food_urgent, 0);
        } else {
            hBinding.tvSolidFoodState.setCompoundDrawablesWithIntrinsicBounds(0, 0, 0, 0);
        }

        if (device.getCatStripsState() != 1) {
            hBinding.tvCatStripsState.setCompoundDrawablesWithIntrinsicBounds(0, 0, R.drawable.ic_home_device_food_urgent, 0);
        } else {
            hBinding.tvCatStripsState.setCompoundDrawablesWithIntrinsicBounds(0, 0, 0, 0);
        }
        hBinding.ivCloseVideo.setOnClickListener(v -> {
            closeVideo();
        });
        hBinding.llLookTa.setOnClickListener(v -> {
            hBinding.remoteVideoViewContainer.removeAllViews();
            hBinding.remoteVideoViewContainer1.removeAllViews();
            if (!PermissionManager.checkStoragePermissions(mContext)) {
                requestPermissions(PermissionManager.getStoragePermissions(), 1);
            }else {
                if (device.getOnlineStatus() == 1) {
                    closeVideo();

                    this.deviceId = deviceId;
//                    hBinding.remoteVideoViewContainer.setVisibility(View.VISIBLE);
//                    hBinding.remoteVideoViewContainer1.setVisibility(View.VISIBLE);

                    hBinding.llLookTa.setVisibility(View.GONE);
                    hBinding.ivCloseVideo.setVisibility(View.VISIBLE);
                    hBinding.ivVideoFullScreen.setVisibility(View.VISIBLE);


                    deviceViewModel.getDeviceAccessToken(deviceId, userId);
                    handler.postDelayed(() -> {
                        deviceViewModel.getDeviceAccessToken1(deviceId + "_1", userId * 10000);
                    }, 500);

                } else {
                    Toast.makeText(mContext, "设备不在线", Toast.LENGTH_SHORT).show();
                }
            }
        });

        hBinding.remoteVideoViewContainer1.setOnClickListener(v -> {
            FrameLayout remoteVideoViewContainer = null;
            if(homeDeviceItemBindingMap != null){
                HomeDeviceItemBinding binding = homeDeviceItemBindingMap.get(deviceId);
                if (binding != null) {
                    remoteVideoViewContainer = binding.remoteVideoViewContainer;
                }
            }
            if(remoteVideoViewContainer == null) return;

            FrameLayout remoteVideoViewContainer1 = null;
            if(homeDeviceItemBindingMap != null){
                HomeDeviceItemBinding binding = homeDeviceItemBindingMap.get(deviceId);
                if (binding != null) {
                    remoteVideoViewContainer1 = binding.remoteVideoViewContainer1;
                }
            }
            if(remoteVideoViewContainer1 == null) return;

            switchLines(remoteVideoViewContainer,remoteVideoViewContainer1);
        });

        hBinding.ivVideoFullScreen.setOnClickListener(v -> {
            closeVideo();
            VideoCallActivity.startActivity(mContext, deviceId);
        });

        hBinding.clDeviceInfo.setOnClickListener(v -> {
            DeviceInfoActivity.startActivity(mContext, device.getDeviceId(), device.getDeviceName(), device.getVideoPreviewImage(), device.getVideoPreviewImage1());
        });

        if (device.getOnlineStatus() != 1) {
            MLog.i("设备不在线");
            hBinding.onlineView.setBackground(AppCompatResources.getDrawable(mContext, R.drawable.layout_red_radius));
            hBinding.tvDeviceOnline.setText(mContext.getString(R.string.device_offline));
        } else {
            MLog.i("设备在线");
            hBinding.onlineView.setBackground(AppCompatResources.getDrawable(mContext, R.drawable.layout_green_spot));
            hBinding.tvDeviceOnline.setText(mContext.getString(R.string.device_online));
        }

        if (device.getVideoPreviewImage() != null) {
            GlideUtils.loadRoundedImage(mContext, device.getVideoPreviewImage(), hBinding.ivPhoto);
        }else {
            hBinding.ivPhoto.setImageDrawable(new ColorDrawable(Color.BLACK));
        }

        if (device.getVideoPreviewImage1() != null) {
            GlideUtils.loadRoundedImage(mContext, device.getVideoPreviewImage1(), hBinding.ivPhoto1);
        }else {
            hBinding.ivPhoto1.setImageDrawable(new ColorDrawable(Color.BLACK));
        }
    }
    
    private void initRtc(int type) {
        if (type == 0) {
            FrameLayout remoteVideoViewContainer = null;
            if(homeDeviceItemBindingMap != null){
                HomeDeviceItemBinding binding = homeDeviceItemBindingMap.get(deviceId);
                if (binding != null) {
                    remoteVideoViewContainer = binding.remoteVideoViewContainer;
                }
            }
            if(remoteVideoViewContainer == null) return;
            rtcEngineManager = new RtcEngineManager(mContext, remoteVideoViewContainer, token, deviceId, userId);
            rtcEngineManager.setRtcEngineEventListener(new RtcEngineManager.RtcEngineEventListener() {
                @Override
                public void onJoinChannelSuccess(String channel, int uid, int elapsed) {
                    if(homeDeviceItemBindingMap != null){
                        HomeDeviceItemBinding binding = homeDeviceItemBindingMap.get(deviceId);
                        if (binding != null) {
                            binding.ivPhoto.setVisibility(View.INVISIBLE);
                            binding.remoteVideoViewContainer.setVisibility(View.VISIBLE);
                        }
                    }

                    handler.sendEmptyMessageDelayed(1, 10000);
                }

                @Override
                public void onUserOffline(int uid, int reason) {
                    if(homeDeviceItemBindingMap != null){
                        HomeDeviceItemBinding binding = homeDeviceItemBindingMap.get(deviceId);
                        if (binding != null) {
                            binding.remoteVideoViewContainer.setVisibility(View.INVISIBLE);
                        }
                    }
                }

                @Override
                public void upLoadSuccess(String url) {
                    handler.sendEmptyMessageDelayed(1, 5000);
                }
            });
            rtcEngineManager.joinChannel();
        } else {
            FrameLayout remoteVideoViewContainer1 = null;
            if(homeDeviceItemBindingMap != null){
                HomeDeviceItemBinding binding = homeDeviceItemBindingMap.get(deviceId);
                if (binding != null) {
                    remoteVideoViewContainer1 = binding.remoteVideoViewContainer1;
                }
            }
            if(remoteVideoViewContainer1 == null) return;
            rtcEngineManager1 = new RtcEngineManager(mContext, remoteVideoViewContainer1, token1, deviceId + "_1", userId * 10000);
            rtcEngineManager1.setRtcEngineEventListener(new RtcEngineManager.RtcEngineEventListener() {
                @Override
                public void onJoinChannelSuccess(String channel, int uid, int elapsed) {
                    if(homeDeviceItemBindingMap != null){
                        HomeDeviceItemBinding binding = homeDeviceItemBindingMap.get(deviceId);
                        if (binding != null) {
                            binding.ivPhoto1.setVisibility(View.INVISIBLE);
                            binding.remoteVideoViewContainer1.setVisibility(View.VISIBLE);
                        }
                    }
                }

                @Override
                public void onUserOffline(int uid, int reason) {
                    if(homeDeviceItemBindingMap != null){
                        HomeDeviceItemBinding binding = homeDeviceItemBindingMap.get(deviceId);
                        if (binding != null) {
                            binding.remoteVideoViewContainer1.setVisibility(View.INVISIBLE);
                        }
                    }
                }

                @Override
                public void upLoadSuccess(String url) {
                    handler.sendEmptyMessageDelayed(1, 5000);
                }
            });
            rtcEngineManager1.joinChannel();
        }
    }

    Handler handler = new Handler(new Handler.Callback() {
        @Override
        public boolean handleMessage(@NonNull Message msg) {
            int what = msg.what;
            if (what == 0) {
                deviceViewModel.getUserDevice();
                mViewModel.getAppBanner();
                handler.sendEmptyMessageDelayed(0, 60000);
            } else if (what == 1) {
                if (rtcEngineManager != null && rtcEngineManager1 != null && (!TextUtils.isEmpty(rtcEngineManager.getAliImagePath()) || !TextUtils.isEmpty(rtcEngineManager.getAliImagePath()))) {
                    deviceViewModel.uploadDeviceVideoImg(deviceId, rtcEngineManager.getAliImagePath(), rtcEngineManager1.getAliImagePath());
                } else {
                    handler.sendEmptyMessageDelayed(1, 2000);
                }
            }
            return false;
        }
    });

    @Subscribe(threadMode = ThreadMode.MAIN)
    public void onMessageEvent(LoginOut event) {
        handler.removeMessages(0);
    }

    @Subscribe(threadMode = ThreadMode.MAIN)
    public void onMessageEvent(Device event) {
        handler.removeMessages(0);
        handler.sendEmptyMessage(0);
        rtcEngineManager.setEnableSpeakerphone(true);
    }

    @Override
    public void onResume() {
        handler.sendEmptyMessage(0);
        mViewModel.getMsgList(20, 1, 0, 0);
        super.onResume();
    }

    @Override
    public void onPause() {
        handler.removeMessages(0);
        handler.removeCallbacksAndMessages(null);
        rtcEngineManager = null;
        rtcEngineManager1 = null;

        closeVideo();
        super.onPause();
    }

    @Override
    protected void initView() {
        mBinding.ivAddDevice.setOnClickListener(v -> {
            DeviceNetworkOneActivity.startActivity(mContext);
        });
        mBinding.llAddDevice.setOnClickListener(v -> {
            DeviceNetworkOneActivity.startActivity(mContext);
        });
//        mBinding.rvDeviceList.setNestedScrollingEnabled(false);
//        mBinding.rvDeviceList.setLayoutManager(new LinearLayoutManager(mContext));
//        deviceListAdapter = new HomeDeviceListAdapter(getActivity(), deviceList);
//        deviceListAdapter.setInitRtc(this);
//        mBinding.rvDeviceList.setAdapter(deviceListAdapter);

        mBinding.swipeRefreshLayout.setOnRefreshListener(refreshLayout -> {
            handler.removeMessages(0);
            handler.sendEmptyMessage(0);
        });
        handler.removeMessages(0);
        handler.sendEmptyMessage(0);
//        mBinding.swipeRefreshLayout.autoRefresh();
        mBinding.ivMessage.setOnClickListener(v -> {
            MessageListActivity.startActivity(mContext);
        });
        closeVideo();
    }

    @Override
    public void networkStatus(boolean isConnected) {

    }

    @Override
    public void networkType(int type) {

    }

    public void closeVideo() {
        if(homeDeviceItemBindingMap != null){
            HomeDeviceItemBinding binding = homeDeviceItemBindingMap.get(deviceId);
            if (binding != null) {
                binding.ivPhoto.setVisibility(View.VISIBLE);
                binding.ivPhoto1.setVisibility(View.VISIBLE);
                binding.remoteVideoViewContainer.setVisibility(View.GONE);
                binding.remoteVideoViewContainer1.setVisibility(View.GONE);

                binding.ivPhoto.setVisibility(View.VISIBLE);
                binding.llLookTa.setVisibility(View.VISIBLE);
                binding.remoteVideoViewContainer.setVisibility(View.INVISIBLE);
                binding.ivCloseVideo.setVisibility(View.INVISIBLE);
                binding.ivVideoFullScreen.setVisibility(View.INVISIBLE);
            }
        }

        if (rtcEngineManager != null) {
            rtcEngineManager.closeVideo();
        }
        if (rtcEngineManager1 != null) {
            rtcEngineManager1.closeVideo();
        }
        rtcEngineManager = null;
        rtcEngineManager1 = null;
    }


    public boolean switchLines(FrameLayout remoteVideoViewContainer,FrameLayout remoteVideoViewContainer1) {

        ViewGroup parent = (ViewGroup) remoteVideoViewContainer1.getParent();

        if (!(parent instanceof ConstraintLayout)) return true;
        ConstraintLayout.LayoutParams paramsA = (ConstraintLayout.LayoutParams) remoteVideoViewContainer.getLayoutParams();
        ConstraintLayout.LayoutParams paramsB = (ConstraintLayout.LayoutParams) remoteVideoViewContainer1.getLayoutParams();

        ConstraintLayout.LayoutParams temp = new ConstraintLayout.LayoutParams(paramsA);
        remoteVideoViewContainer.setLayoutParams(paramsB);
        remoteVideoViewContainer1.setLayoutParams(temp);

        int indexA = parent.indexOfChild(remoteVideoViewContainer);
        int indexB = parent.indexOfChild(remoteVideoViewContainer1);

        parent.removeView(remoteVideoViewContainer);
        parent.removeView(remoteVideoViewContainer1);

        if (indexA < indexB) {
            parent.addView(remoteVideoViewContainer1, indexA);
            parent.addView(remoteVideoViewContainer, indexB);
        } else {
            parent.addView(remoteVideoViewContainer, indexB);
            parent.addView(remoteVideoViewContainer1, indexA);
        }
        return true;
    }
}